package com.symone.webcms.service.impl;

import com.symone.webcms.mapper.DataExtMapper;
import com.symone.webcms.model.DataContent;
import com.symone.webcms.mapper.DataContentMapper;
import com.symone.webcms.model.DataExt;
import com.symone.webcms.model.ModuleField;
import com.symone.webcms.model.vo.DataContentVO;
import com.symone.webcms.service.DataContentService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.symone.webcms.util.FrameworkUtil;
import com.xiaoleilu.hutool.json.JSONObject;
import com.xiaoleilu.hutool.json.JSONUtil;
import com.xiaoleilu.hutool.util.StrUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import javax.validation.constraints.NotNull;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *　　
 *   @description : Content 服务实现类
 *   ---------------------------------
 * 	 @author Archer Chu
 *   @since 2019-03-24
 */
@Service
public class DataContentServiceImpl extends ServiceImpl<DataContentMapper, DataContent> implements DataContentService {

    @Autowired
    private DataExtMapper extMapper;

    @Override
    public Page<DataContent> findPage(Page<DataContent> page, Wrapper<DataContent> content) {
        List<DataContent> result = baseMapper.selectPage(page,content);
        page.setRecords(result);
        return page;
    }

    @Override
    public List<DataContent> findAll() {
        Wrapper<DataContent> ew = new EntityWrapper<DataContent>();
        ew.where("deleted=0");
        return baseMapper.selectList(ew);
    }

    @Override
    @Transactional
    public boolean delete(long id) {
        if( extMapper.delete(new EntityWrapper<DataExt>().eq("cid",id)) > 0 ) {
            return baseMapper.deleteById(id) > 0;
        }
        return false;
    }

    @Override
    public boolean deleteFlagById(long id) {
        return baseMapper.deleteFlagById(id);
    }

    @Override
    public int clear() {
        return baseMapper.delete(new EntityWrapper<DataContent>().eq("deleted" ,1));
    }

    @Override
    @Transactional
    public boolean add(HttpServletRequest request, @NotNull(message = "用户名不能为空") String userName) {
        String module = request.getParameter("module");
        DataContent dataContent = createContent(request,userName);
        List<ModuleField> fields = FrameworkUtil.getFieldsByModel(module);
        if (baseMapper.insert(dataContent) > 0) {
            for (ModuleField field : fields) {
                saveExtData(request,dataContent,field);
            }
            return true;
        } else {
            return false;
        }
    }

    @Override
    @Transactional
    public boolean update(HttpServletRequest request, @NotNull(message = "用户名不能为空") String userName) {
        String module = request.getParameter("module");
        DataContent dataContent = createContent(request,userName);
        List<ModuleField> fields = FrameworkUtil.getFieldsByModel(module);
        if (baseMapper.updateById(dataContent) > 0) {
            int count = extMapper.delete(new EntityWrapper<DataExt>()
                    .eq("cid",dataContent.getId())
                    .and()
                    .eq("lang",dataContent.getLang())
                    .and()
                    .eq("module",dataContent.getModule())
            );
            if(count > 0) {
                for (ModuleField field : fields) {
                    saveExtData(request, dataContent, field);
                }
            }
            return true;
        } else {
            return false;
        }
    }

    @Override
    public Page<DataContentVO> selectConditionPage(Page<DataContentVO> page, String lang, String module, Long groupId, String key, String val) {
        List<DataContentVO> list = baseMapper.selectConditionPage(page,lang,module,groupId,key,val);
        page.setRecords(list);
        return page;
    }

    private DataContent createContent(HttpServletRequest request,String userName){
        String id = request.getParameter("id");
        String lang = request.getParameter("lang");
        String module = request.getParameter("module");
        String state = request.getParameter("state");
        String groupId = request.getParameter("groupId");

        DataContent dataContent = new DataContent();
        if(StrUtil.isNotEmpty(id)) {
            dataContent.setId(Long.valueOf(id));
        }
        dataContent.setLang(lang);
        dataContent.setModule(module);
        dataContent.setCreateUser(userName);
        dataContent.setState(state == null ? 0 : Integer.valueOf(state));
        dataContent.setGroupId(Long.valueOf(groupId));
        dataContent.setUpdateUser(userName);

        JSONObject params = JSONUtil.createObj();
        List<ModuleField> fields = FrameworkUtil.getFieldsByModel(module);
        for (ModuleField field : fields) {
            String extName = field.getName();
            String extValue = request.getParameter(field.getName());
            if(field.getListed() == 1){
                params.put(extName,extValue);
            }
        }
        dataContent.setViews(params.toString());
        return dataContent;
    }

    private void saveExtData(HttpServletRequest request,DataContent dataContent,ModuleField field){

        DataExt contentExt = new DataExt();
        contentExt.setCid(dataContent.getId());
        contentExt.setExtName(field.getName());
        contentExt.setLang(dataContent.getLang());
        contentExt.setModule(dataContent.getModule());
        contentExt.setExtValue(request.getParameter(field.getName()));
        contentExt.setCreateTime(new Date());
        contentExt.setUpdateTime(new Date());
        extMapper.insert(contentExt);
    }

}
